package com.lcu.wl.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.lcu.wl.common.utils.PageUtils;
import com.lcu.wl.common.utils.Query;
import com.lcu.wl.modules.sys.entity.Role;
import com.lcu.wl.modules.sys.mapper.RoleMapper;
import com.lcu.wl.modules.sys.service.IRoleMenuService;
import com.lcu.wl.modules.sys.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lcu.wl.modules.sys.service.IUserRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 角色管理 服务实现类
 * </p>
 *
 * @author wanglei
 * @since 2021-01-15
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Autowired
    private IUserRoleService iUserRoleService;

    @Autowired
    private IRoleMenuService iRoleMenuService;

    @Override
    public List<Long> queryRoleIdList(Long createUserId) {
        return baseMapper.queryRoleIdList(createUserId);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String roleName = (String)params.get("roleName");
        Long createUserId = (Long)params.get("createUserId");

        IPage<Role> page = this.page(
                new Query<Role>().getPage(params),
                new QueryWrapper<Role>()
                        .like(StringUtils.isNotBlank(roleName),"role_name", roleName)
                        .eq(createUserId != null,"create_user_id", createUserId)
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveRole(Role role) {
        role.setCreateTime(new Date());
        this.save(role);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] roleIds) {
        //删除角色
        this.removeByIds(Arrays.asList(roleIds));

        //删除角色与菜单对应关系
        iRoleMenuService.delByRoleIdsBatch(roleIds);

        //删除角色与用户关联
        iUserRoleService.delByRoleIdsBatch(roleIds);
    }
}
